package cn.lblbc.todo

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import java.text.SimpleDateFormat
import java.util.Locale

class TaskItemAdapter(
    private val tasks: List<Task>,
    private val onTaskCheckedChangeListener: (Task, Boolean) -> Unit,
    private val onTaskClickListener: (Task) -> Unit
) : RecyclerView.Adapter<TaskItemAdapter.TaskItemViewHolder>() {

    class TaskItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val taskCheckBox: CheckBox = itemView.findViewById(R.id.taskCheckBox)
        val taskTitleTextView: TextView = itemView.findViewById(R.id.taskTitleTextView)
        val taskTimeTextView: TextView = itemView.findViewById(R.id.taskTimeTextView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskItemViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_task_row, parent, false)
        return TaskItemViewHolder(view)
    }

    override fun onBindViewHolder(holder: TaskItemViewHolder, position: Int) {
        val task = tasks[position]
        
        holder.taskCheckBox.isChecked = task.isCompleted
        holder.taskTitleTextView.text = task.title
        
        // 显示时间点（不含日期）
        if (task.dueDate != null) {
            val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
            holder.taskTimeTextView.text = timeFormat.format(task.dueDate)
        } else {
            holder.taskTimeTextView.text = ""
        }
        
        // 设置复选框状态改变监听器
        holder.taskCheckBox.setOnCheckedChangeListener { _, isChecked ->
            onTaskCheckedChangeListener(task, isChecked)
        }
        
        // 设置整个项目的点击监听器
        holder.itemView.setOnClickListener {
            onTaskClickListener(task)
        }
    }

    override fun getItemCount(): Int = tasks.size
}